#!/bin/sh
#
# Author ： hbaolong@vip.qq.com
#
# Function : 生成HASH5（##### ）的文件。
#
#
#

if [ $# -ne 0 ]; then
	echo "Usage: this is a empty shell."
	exit
fi

if [ ! -e config ]; then
	echo "no config file"
	exit -1
fi

source config

# 处理只有单个文件的问题


grep "^##### " `ls -l |sed -e "/^l/d" |grep $tag |awk '{print $NF}'` |sed -e "/hash.*html/d">hash.tmp

if [ ! -e hash ]; then
#	echo "no hash files"
	rm -f hash.tmp
	exit -2
fi

# 检测最新编号

counter=`ls hash|grep ".md" | sed -e "/index.md/d"  |tail -1 |sed -e "s/\..*//g"|sed -e "s/^0*//g"`

#cat hash.tmp

hashfiletopen=""

while IFS= read -r line; 
do

	((counter=counter+1))

	hashfilename=`printf "%04d\n" $counter`

	hashfile=hash/$hashfilename".md"

	content=`echo $line | sed -e "s/.*##### //g"`

	# 生成空的（带模板的）hash文件

	echo "% " $content >$hashfile
	echo "" >>$hashfile

	if [ -e hash/TEMPLE ]; then 
		cat hash/TEMPLE >>$hashfile
	fi


	hashfiletopen=$hashfiletopen" "$hashfile

	if [ $allchapter -eq 1 ]; then 
		bookfile=`ls $tag*.md`
	else
		bookfile=`echo $line|awk -F:##### '{print $1}'`
	fi

	sed "s/^##### $content/##### \[$content\]\(\.\/hash\/$hashfilename\.html\)/g" $bookfile >$bookfile.tmp

	mv $bookfile.tmp $bookfile

done <hash.tmp

rm -f hash.tmp

# 重新生成index.md

if [[ ! "$hashfiletopen" == "" ]]; then

	indexfile="hash/index.md"

	echo "% $bookname HASH5目录" > $indexfile

	echo "" >> $indexfile

	grep "^##### " `ls -l $tag*.md |  sed -e "/^l/d" |awk '{print $NF}'`| sed -e "s/.*##### //g" |sed -e "s/hash\///g" |awk -F\. '{printf substr($(NF-1),2,length($(NF-1)));print "." $0 "\n"}' >tmp.md 

	sed -e "/^$/d" tmp.md |sort -g |awk '{print $0 "\n"}'>> $indexfile

	rm -f tmp.md

fi



# 生成html

if [ ! -e $basedir$url/hash ]; then
	mkdir $basedir$url/hash
fi

for files in `find . -mnewer timetag |grep hash|grep md`
do
	htmlfile=`echo $files |sed -e "s/\.md$/\.html/g"`

	echored $files

	grep "^% " $files>tmp.md

	commcode bookheader >>tmp.md
	echo "" >>tmp.md
	cat $files |sed -e "/^% /d" >>tmp.md

	commcode bookfooter >>tmp.md

	pandoc -s tmp.md -o $htmlfile

	if [ ! -e $basedir$url/hash ]; then

		mkdir -p $basedir$url/hash

	fi

	mv $htmlfile $basedir$url/hash

done

echo $hashfiletopen |xargs subl 

rm -f tmp.md
